import 'package:flutter/foundation.dart';
import '../../data/api/auth_api.dart';
import '../../data/models/api_response.dart';
import '../../data/models/user.dart';
import '../../core/exceptions/app_exception.dart';

/// 认证状态提供者，管理用户登录状态
class AuthProvider with ChangeNotifier {
  final AuthApi _authApi;

  User? _currentUser;
  String? _accessToken;
  String? _refreshToken;
  bool _isAuthenticated = false;
  bool _isLoading = false;
  String? _errorMessage;

  /// 当前登录用户
  User? get currentUser => _currentUser;

  /// 是否已认证
  bool get isAuthenticated => _isAuthenticated;

  /// 是否正在加载
  bool get isLoading => _isLoading;

  /// 访问令牌
  String? get accessToken => _accessToken;

  /// 错误信息
  String? get errorMessage => _errorMessage;

  AuthProvider({AuthApi? authApi}) : _authApi = authApi ?? AuthApi();

  /// 用户注册
  Future<void> register({
    required String username,
    required String email,
    required String password,
  }) async {
    _setLoading(true);
    _clearError();

    try {
      await _authApi.register(
        username: username,
        email: email,
        password: password,
      );
    } catch (e) {
      _setError(e is AppException ? e.message : '注册失败: ${e.toString()}');
      rethrow;
    } finally {
      _setLoading(false);
    }
  }

  /// 用户登录
  Future<void> login({
    required String username,
    required String password,
  }) async {
    _setLoading(true);
    _clearError();

    try {
      final response = await _authApi.login(
        username: username,
        password: password,
      );

      // 检查响应中的data是否为空
      if (response.data == null) {
        throw const ApiException('登录成功但服务器返回的用户数据为空');
      }

      _handleAuthResponse(response.data!);
    } catch (e) {
      debugPrint('登录失败: $e');
      _setError(e is AppException ? e.message : '登录失败: ${e.toString()}');
      rethrow;
    } finally {
      _setLoading(false);
    }
  }

  /// 注销登录
  void logout() {
    _currentUser = null;
    _accessToken = null;
    _refreshToken = null;
    _isAuthenticated = false;
    _clearError();
    notifyListeners();
  }

  /// 刷新令牌
  Future<void> refreshToken() async {
    if (_refreshToken == null) {
      throw const TokenExpiredException('没有有效的刷新令牌');
    }

    _setLoading(true);
    _clearError();

    try {
      final response = await _authApi.refreshToken(_refreshToken!);

      // 检查响应中的data是否为空
      if (response.data == null) {
        throw const ApiException('刷新令牌成功但服务器返回的用户数据为空');
      }

      _handleAuthResponse(response.data!);
    } catch (e) {
      _setError(e is AppException ? e.message : '刷新令牌失败: ${e.toString()}');
      rethrow;
    } finally {
      _setLoading(false);
    }
  }

  /// 处理认证响应
  void _handleAuthResponse(AuthResponse authResponse) {
    _currentUser = authResponse.user;
    _accessToken = authResponse.accessToken;
    _refreshToken = authResponse.refreshToken;
    _isAuthenticated = true;
    _clearError();
    notifyListeners();
  }

  /// 设置加载状态
  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  /// 设置错误信息
  void _setError(String message) {
    _errorMessage = message;
    notifyListeners();
  }

  /// 清除错误信息
  void _clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  @override
  void dispose() {
    super.dispose();
    // 关闭API客户端连接
    _authApi.dispose();
  }
}
